import logging
import tkinter as tk
from tkinter import ttk, messagebox

class ConfigTab:

    def __init__(self, base):
        self.base = base
        self.init_data()

    def init_data(self):
        # 初始化配置项（确保所有必要配置都存在）
        if not self.base.config.has_section('api'):
            self.base.config.add_section('api')
        if not self.base.config.has_section('account'):
            self.base.config.add_section('account')

        # API配置默认值
        self.api_config = {
            'customs179_url': self.base.config.get('api', 'customs179_url', fallback='https://customs.chinaport.gov.cn/ceb2grab/grab/realTimeDataUpload'),
            'timeout': self.base.config.get('api', 'timeout', fallback='30'),
            'check_url': self.base.config.get('api', 'check_url', fallback='https://dev-mapi.tdfsm.com/callback/customs179/checkHXA'),
            'back_url': self.base.config.get('api', 'back_url', fallback='https://customs-mapi.tdfsm.com/callback/customs179/back')
        }

        # 账户配置默认值
        self.account_config = {
            'customs_no': self.base.config.get('account', 'customs_no', fallback=''),
            'password': self.base.config.get('account', 'password', fallback='88888888'),
            'cert_no': self.base.config.get('account', 'cert_no', fallback='')
        }

    def  setup_config_tab(self, parent):
        """设置系统设置选项卡，用于修改配置"""
        # 创建主框架
        main_frame = ttk.Frame(parent, padding=10)
        main_frame.pack(fill='both', expand=True)

        # 创建滚动窗口（防止内容过多时溢出）
        canvas = tk.Canvas(main_frame)
        scrollbar = ttk.Scrollbar(main_frame, orient="vertical", command=canvas.yview)
        scrollable_frame = ttk.Frame(canvas)

        # 配置滚动区域
        scrollable_frame.bind(
            "<Configure>",
            lambda e: canvas.configure(scrollregion=canvas.bbox("all"))
        )
        canvas.create_window((0, 0), window=scrollable_frame, anchor="nw")
        canvas.configure(yscrollcommand=scrollbar.set)

        # 布局滚动组件
        canvas.pack(side="left", fill="both", expand=True)
        scrollbar.pack(side="right", fill="y")

        # API配置区域
        api_frame = ttk.LabelFrame(scrollable_frame, text="API配置", padding=10)
        api_frame.pack(fill='x', pady=(0, 10), padx=5)

        # 账户配置区域
        account_frame = ttk.LabelFrame(scrollable_frame, text="账户配置", padding=10)
        account_frame.pack(fill='x', pady=(0, 10), padx=5)

        # 配置输入框标签和条目
        config_fields = [
            # (区域, 键, 标签文本, 是否密码)
            ('api', 'customs179_url', '海关179接口URL', False),
            ('api', 'timeout', '请求超时时间(秒)', False),
            ('api', 'check_url', '校验接口URL', False),
            ('api', 'back_url', '回调接口URL', False),
            ('account', 'customs_no', '海关备案号', False),
            ('account', 'password', '卡介质密码', False),
            ('account', 'cert_no', '证书编号', False),
        ]

        # 存储输入框引用的字典
        self.config_entries = {}

        # 分别记录两个区域的行索引
        api_row = 0
        account_row = 0

        # 创建输入框
        for section, key, label, is_password in config_fields:
            # 根据区域选择父容器和行索引
            if section == 'api':
                parent_frame = api_frame
                row = api_row
                api_row += 1
            else:
                parent_frame = account_frame
                row = account_row
                account_row += 1

            # 创建标签
            ttk.Label(parent_frame, text=label).grid(
                row=row, column=0, sticky='w', padx=5, pady=5)

            # 根据是否为密码字段选择输入框类型
            if is_password:
                entry = ttk.Entry(
                    parent_frame,
                    show='*',
                    width=60
                )
            else:
                entry = ttk.Entry(
                    parent_frame,
                    width=60
                )

            # 填充当前值
            if section == 'api':
                entry.insert(0, self.api_config[key])
            else:
                entry.insert(0, self.account_config[key])

            entry.grid(row=row, column=1, sticky='w', padx=5, pady=5)
            self.config_entries[f"{section}_{key}"] = entry

        # 按钮区域
        button_frame = ttk.Frame(scrollable_frame)
        button_frame.pack(fill='x', pady=15)

        # 保存按钮
        save_btn = ttk.Button(
            button_frame,
            text="保存配置",
            command=self.save_current_config,
            width=20
        )
        save_btn.pack(side='left', padx=10)

        # 配置说明
        desc_label = ttk.Label(
            scrollable_frame,
            text="提示：修改配置后将立即生效，部分设置可能需要重启程序",
            foreground="gray"
        )
        desc_label.pack(anchor='w', padx=5, pady=5)


    def save_current_config(self):
        """保存当前界面上的配置到内存和文件"""
        # 更新内存中的配置
        try:
            # 更新API配置
            self.api_config['customs179_url'] = self.config_entries['api_customs179_url'].get()
            self.api_config['timeout'] = self.config_entries['api_timeout'].get()
            self.api_config['check_url'] = self.config_entries['api_check_url'].get()
            self.api_config['back_url'] = self.config_entries['api_back_url'].get()

            # 更新账户配置
            self.account_config['customs_no'] = self.config_entries['account_customs_no'].get()
            self.account_config['password'] = self.config_entries['account_password'].get()
            self.account_config['cert_no'] = self.config_entries['account_cert_no'].get()

            # 保存到文件
            self.save_config()

        except Exception as e:
            messagebox.showerror("错误", f"处理配置时出错: {str(e)}")
            logging.error(f"处理配置时出错: {e}")

    def save_config(self):
        """保存配置到文件"""
        try:
            # 更新配置对象
            for key, value in self.api_config.items():
                self.base.config.set('api', key, value)
            for key, value in self.account_config.items():
                self.base.config.set('account', key, value)

            # 写入文件
            with open(self.base.config_path, 'w', encoding='utf-8') as f:
                self.base.config.write(f)

            messagebox.showinfo("成功", "配置已保存")
            logging.info("配置保存成功")
        except Exception as e:
            messagebox.showerror("错误", f"保存配置失败: {str(e)}")
            logging.error(f"保存配置失败: {e}")